//
//  HDPicturesView.swift
//  HDSwfitWeibo
//
//  Created by wty on 16/4/14.
//  Copyright © 2016年 wty. All rights reserved.
//

import UIKit
import SDWebImage
//cell之间的间距
private let HDPictureViewCellMargin :CGFloat = 4
//cell的最大列数
private let HDPictureViewMaxColumn = 3
//cell的宽高
private let HDPictureViewCellWidth:CGFloat =  (ScreenW-2*cellMargin-(CGFloat(HDPictureViewMaxColumn)-1)*HDPictureViewCellMargin)/CGFloat (HDPictureViewMaxColumn)
private let HDPictureViewCellHeight:CGFloat =  HDPictureViewCellWidth


class HDPicturesView: UICollectionView {
//id
private let ReuseIdentifier = "ReuseIdentifie"
//MARK -初始化方法
    //定义流水布局
  private var  pictureLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    init(){
        super.init(frame: CGRectZero, collectionViewLayout: pictureLayout)
        backgroundColor = UIColor.clearColor()
        //注册cell与设置代理
        registerClass(HDPictureViewCell.self, forCellWithReuseIdentifier:ReuseIdentifier)
        dataSource = self
        delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//MARK -属性观察期设置属性
    var pictureURLs : [NSURL]?{
        didSet{

            let size = calcViewSize()
            //重新更新pictureView的约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            //cell重用  导致重用之前高度  刷新数据就好
            reloadData()
        }
    }
    //计算图片宽高
    private func calcViewSize() ->CGSize{
        //layout布局
        pictureLayout.itemSize = CGSize(width: HDPictureViewCellWidth, height:  HDPictureViewCellHeight)
        pictureLayout.minimumInteritemSpacing = 0
        pictureLayout.minimumLineSpacing = 0
        //判断图片数量
        let  count = pictureURLs?.count ?? 0
        //1.没有图片
        if count  == 0{
            HDPrint("没有图片")
            return CGSizeZero
        }
        //2.1张图片
        if  count == 1{
            //设置默认大小
            var size = CGSize(width: HDPictureViewCellWidth, height: HDPictureViewCellHeight)
            //获取图片的url
            let url = pictureURLs!.first!
            //根据urlString 去拿缓存图片
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url.absoluteString
                ) {
                    //SDWebImage 框架在3.7.3之后 自动图片像素改为@方式  根据苹果不同屏幕自动设置2@或者3@方式
                    //所以这里图片的小要改为乘与原来的缩放比例
                    size = image.size
                    UIScreen.mainScreen().scale
                    size = CGSize(width: size.width*UIScreen.mainScreen().scale, height: size.height*UIScreen.mainScreen().scale)
            }
            //如果图片太小  设置最小宽度为40
            if size.width<40 {
                size.width = 40
            }
            //如果图片超过屏幕一半 设置最大宽度为屏幕一半
            if size.width > ScreenW*0.5{
                size.width =  ScreenW*0.5
            }
            pictureLayout.itemSize = size
            
            return size
        }
        pictureLayout.minimumInteritemSpacing = HDPictureViewCellMargin
        pictureLayout.minimumLineSpacing = HDPictureViewCellMargin
        //3.多张图片 2张或者4张图片显示两列  其他显示3列
        //3.1计算出行数和列数
        //列数
        var column = HDPictureViewMaxColumn
        if count == 2 || count == 4 {
            column = 2
        }
        //行数
        let row = (count + column - 1) / column
        //3.2计算宽度和高度
        let width = CGFloat( column)*HDPictureViewCellWidth + (CGFloat(column)-1)*HDPictureViewCellMargin
        let height = CGFloat(row)*HDPictureViewCellHeight + (CGFloat(row)-1)*HDPictureViewCellMargin
        return  CGSize(width: width, height: height)
    }
    
}
//代理方法
extension HDPicturesView:UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(self.pictureURLs?.count)
        return self.pictureURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HDPictureViewCell
        cell.imageURL = self.pictureURLs?[indexPath.item]
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
            let  browser = SDPhotoBrowser()
            browser.sourceImagesContainerView = collectionView
            browser.imageCount = self.pictureURLs?.count ?? 0
            browser.currentImageIndex = indexPath.item
            browser.delegate = self
            browser.show()
    }
}
extension HDPicturesView : SDPhotoBrowserDelegate{
    //返回临时占位图片 即原来的小图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        //获取cell
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = cellForItemAtIndexPath(indexPath)as! HDPictureViewCell
        let image = cell.imageView.image ?? UIImage(named: "avatar_default")
        return image
    }
    //返回高质量
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let thumbnaliUrl = pictureURLs?[index].absoluteString
        let newUrlString = thumbnaliUrl?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: newUrlString!)
    }
}
